#-*-coding:utf-8 -*-
from ast import Delete
import time
import os
from datetime import date
import shutil
import psutil
import signal
from interval import Interval
from datetime import datetime
import csv
import json
import pyautogui
from threading import Thread,Event
from bypy import ByPy  
import logging
import logging.handlers
import threading
import tkinter as tk
from pid.decorator import pidfile

config = {
    "interval_time":6,
    "englishclass_list":[
        "",
        "08:50:00-09:40:00",
        "08:35:00-09:25:00",
        "08:35:00-09:25:00",
        "08:35:00-09:25:00",
        "08:35:00-09:25:00",
        ""
    ],
    "rest_time": [
        "12:00:00-14:00:00",
        "17:00:00-19:00:00",
        "19:00:00-24:00:00"
    ],
    "time_arg": [
        "07:30:00-22:30:00"
    ],
    "game_proc": [
        "WPFLauncher.exe",
        "Genshin Impact Cloud Game.exe",
        "douyin.exe",
        "哔哩哔哩.exe",
        "QQ.exe",
        "douyin_tray.exe",
        "QyX64Host.exe",
        "QiyiService.exe"
    ],
    "brower_proc": [
        "2345Explorer.exe",
        "TSBrowser.exe",
        "DCBrowser.exe",
        "UCAgent.exe",
        "UCBrowser.exe",
        "ChromeCore.exe",
        "360se.exe",
        "QQBrowser.exe",
        "firefox.exe",
        "SogouExplorer.exe",
        "msedge.exe",
        "37abc.exe",
        "FlashCenter.exe",
        "FCBrowser.exe",
        "FCBrowserManager.exe",
        "Thunder.exe",
        "QyClient.exe",
        "chrome.exe",
        "GptBrowser.exe"
    ],
    "music_proc": [
        "KuGoue.exe",
        "QQmusic.exe"
    ],
    "all_processes": [
        "System Idle Process",
        "System",
        "Registry",
        "smss.exe",
        "services.exe",
        "conhost.exe",
        "audiodg.exe",
        "lsass.exe",
        "csrss.exe",
        "svchost.exe",
        "fontdrvhost.exe",
        "wininit.exe",
        "winlogon.exe",
        "fontdrvhost.exe",
        "dwm.exe",
        "yundetectservice.exe",
        "IAStorDataMgrSvc.exe",
        "QAAgent.exe",
        "QAAdminAgent.exe",
        "AutoScrShot.exe",
        "NVDisplay.Container.exe",
        "QQPCRTP.exe",
        "qmbsrv.exe",
        "TSVNCache.exe",
        "explorer.exe",
        "MemCompression",
        "igfxCUIService.exe",
        "taskhostw.exe",
        "spoolsv.exe",
        "SystemSettings.exe",
        "CRMUploader.exe",
        "wlanext.exe",
        "AvidAppManHelper.exe",
        "SogouCloud.exe",
        "ibtsiva.exe",
        "AppleMobileDeviceService.exe",
        "fpprotect.exe",
        "IntelCpHDCPSvc.exe",
        "EvtEng.exe",
        "ijplmsvc.exe",
        "mDNSResponder.exe",
        "RegSrvc.exe",
        "jhi_service.exe",
        "FlashHelperService.exe",
        "PanDhcpDns.exe",
        "TsService.exe",
        "jenkins.exe",
        "service.exe",
        "wireguard.exe",
        "WkNative.exe",
        "wireguard.exe",
        "Trapmnnt.exe",
        "LMSRVNT.EXE",
        "mysqld.exe",
        "ZeroConfigService.exe",
        "QQProtect.exe",
        "sesvr.exe",
        "QtWebEngineProcess.exe",
        "QtWebEngineProcess.exe",
        "WkDetail.exe",
        "Tencentdl.exe",
        "dasHost.exe",
        "IntelCpHeciSvc.exe",
        "wireguard.exe",
        "splwow64.exe",
        "unsecapp.exe",
        "SearchApp.exe",
        "baidunetdiskhost.exe",
        "WmiPrvSE.exe",
        "SearchFilterHost.exe",
        "sihost.exe",
        "PresentationFontCache.exe",
        "CNQMMAIN.EXE",
        "LockApp.exe",
        "taskhostw.exe",
        "TextInputHost.exe",
        "ctfmon.exe",
        "DCBrowserSvr.exe",
        "explorer.exe",
        "igfxEM.exe",
        "QtWebEngineProcess.exe",
        "QQPCTray.exe",
        "AvidAppManHelper.exe",
        "baidunetdisk.exe",
        "java.exe",
        "Code.exe",
        "ChsIME.exe",
        "QQPCRealTimeSpeedup.exe",
        "QtWebEngineProcess.exe",
        "StartMenuExperienceHost.exe",
        "RuntimeBroker.exe",
        "DMWakeup.exe",
        "SearchIndexer.exe",
        "ApplicationFrameHost.exe",
        "WmiPrvSE.exe",
        "QASvc.exe",
        "igfxext.exe",
        "SecurityHealthSystray.exe",
        "SecurityHealthService.exe",
        "dllhost.exe",
        "RAVCpl64.exe",
        "ShellExperienceHost.exe",
        "RAVBg64.exe",
        "SgrmBroker.exe",
        "KuGou.exe",
        "KGService.exe",
        "smartscreen.exe",
        "QALockHandler.exe",
        "unsecapp.exe",
        "cmd.exe",
        "Cortana.exe",
        "sesvc.exe",
        "baidunetdiskhost.exe",
        "ChromeCoreSvr.exe",
        "SogouImeBroker.exe",
        "SeAppService.exe",
        "PCCMFSDM.exe",
        "python.exe",
        "Avid Link.exe",
        "jusched.exe",
        "wemeetapp.exe",
        "CNQMUPDT.EXE",
        "SearchProtocolHost.exe",
        "powershell.exe",
        "timeout.exe",
        "ClassIn.exe",
        "ClassIn Helper.exe",
        "DingTalk.exe",
        "TBSWebRenderer.exe",
        "wps.exe",
        "wpscloudsvr.exe",
        "QuickSeeTray.exe",
        "WkMnex.exe",
        "xnnexternal.exe",
        "GoogleUpdate.exe",
        "DingTalkSnippingTool.exe",
        "monPC.exe",
        "PrintIsolationHost.exe",
        "MoUsoCoreWorker.exe",
        "TiWorker.exe",
        "TrustedInstaller.exe",
        "Wkskech.exe",
        "wermgr.exe",
        "WemeetUpdateSvc.exe",
        "SystemSettingsBroker.exe",
        "PeopleExperienceHost.exe",
        "SGTool.exe",
        "tblive.exe",
        "kashost.exe",
        "乐学培优.exe",
        "backgroundTaskHost.exe",
        "Windows-KB890830-x64-V5.108.exe",
        "GDzuhral.exe",
        "wmsvc.exe",
        "FlashCenterSa.exe",
        "GDSevicat.exe",
        "AcerRegistrationBackGroundTask.exe",
        "Microsoft.Photos.exe",
        "2345RTProtect.exe",
        "2345SafeCenterSvc.exe",
        "LogonUI.exe",
        "OneDrive.exe",
        "WinStore.App.exe",
        "rundll32.exe",
        "fastpdf.exe",
        "YourPhone.exe",
        "kvipgui.exe",
        "yundetectservice.exe",
        "wmtray.exe",
        "TheWorld.exe",
        "kernelupdate.exe",
        "FileCoAuth.exe",
        "prscrn.exe",
        "promecefpluginhost.exe",
        "CorelDRAW X4_30913566.exe",
        "notepad++.exe",
        "ComputerZTray.exe",
        "wmscleaner.exe",
        "VSSVC.exe",
        "Taskmgr.exe",
        "WemeetUpgradeHelper.exe",
        "hdw_disk_scan.exe",
        "ComputerZService.exe",
        "computercenter.exe",
        "wmsoftmgr.exe",
        "wmbusdata64.exe",
        "2345SoftMgr.exe",
        "chrome.exe",
        "ChromeCore.exe",
        "MsMpEng.exe",
        "ToDesk.exe",
        "NisSrv.exe",
        "esif_uf.exe",
        "ToDesk_Service.exe",
        "photolaunch.exe",
        "baidunetdiskrender.exe",
        "LocationNotificationWindows.exe",
        "UserOOBEBroker.exe",
        "designer.exe",
        "MpCmdRun.exe",
        "MpCmdRun.exe",
        "sppsvc.exe",
        "mon_cfg.exe",
        "notepad.exe",
        "EVCapture.exe",
        "DiskInfo64.exe",
        "BCompare.exe",
        "SogouImeLoader.exe",
        "JianyingPro.exe",
        "VEDetector.exe",
        "VEHelper.exe", 
        "parfait_crash_handler.exe",
        "ttdaemon.exe",
        "SSDX.exe",
        "GameBarFTServer.exe",
        "GameBar.exe",
        "PBIDesktop.exe",
        "msedgewebview2.exe", 
        "ttermpro.exe", 
        "WmiApSrv.exe",
        "msmdsrv.exe",
        "mintty.exe", 
        "git.exe", 
        "git-bash.exe", 
        "prevhost.exe", 
        "bash.exe", 
        "git-remote-https.exe",
        "pyinstaller.exe",
        "git-credential-manager-core.exe",
        "sh.exe",
        "GameBarPresenceWriter.exe",
        "SGPicFaceTool.exe",
        "identity_helper.exe",
        "monCfg.exe"
    ]
}

CLOSE_TIME = 3
class message_show(threading.Thread):
    def __init__(self):
        self.myThread=None
        self.myEvent = Event()
        pass
        
    def show_messagebox(self,string,rows=0):
        try:
            # os.environ["DISPLAY"]=":0.0"
            root = tk.Tk()
            root.title('Warning')
            # root.iconbitmap('warning1.ico')
            # root.iconphoto(False, tk.PhotoImage(file='warning.png'))
            H = 180
            W = 400
            size = '%dx%d'%(W,H)
            if rows >= 4:
                size = '%dx%d'%(W,200+(rows-4)*18)
                H = 200+(rows-4)*18
                # print(size)
            root.geometry(size)
            root.resizable(False,False)
            laTxt = tk.Label(root, text=string, font='宋体 -14', pady=8,fg='orangered',justify='left')
            laTxt.place(x=0,y=10,width=W)
            # label.pack()
            
            lbTime = tk.Label(root, font='宋体 -14', fg='green',justify='left',anchor='w')
            lbTime.place(x=10,y=H-30,width=W)
            
            img_png = tk.PhotoImage(file='./image/warning-sign.png')
            lbimg = tk.Label(root,image=img_png,justify='left',anchor='w')
            lbimg.place(x=30,y=40,width=80)                                                                                                      
            # lbimg.pack()
            
            endtime = CLOSE_TIME
            i = 0
            lbTime['text']='the library will be closed in %s:%s second... '%(int((endtime-i)/60),60-i%60)
                
            def auto_close():
                try:
                    endtime = CLOSE_TIME
                    for i in range(1,endtime):
                        if self.myEvent.is_set():
                            break
                        m,s = divmod(endtime-i,60)
                        # h,m = divmod(m,60)
                        lbTime['text']='the library will be closed in %02s:%02s second... '%(m,s)
                        time.sleep(1)

                    # root.destroy()
                except:
                    print('error..')
                    pass
            
            def on_close(index=True):
                if index:
                    self.myEvent.set()
                while(True):
                    if not self.myThread.is_alive():
                        break
                    else:
                        time.sleep(0.5)
                root.destroy()
                    
            # time.sleep(5)    
            self.myThread = threading.Thread(target=auto_close,name='auto close')
            # t.setDaemon(True)
            self.myThread.start()       
                

            # root.protocol('WM_DELETE_WINDOW',root.iconify)
            root.protocol('WM_DELETE_WINDOW',on_close)
            root.after(CLOSE_TIME*1000,on_close,False)
            root.mainloop()
        except:
            print('error')
            pass
    # def do_ring(times):
    #     for i in range(0,times):
    #         os.system("paplay {} --volume=32768".format('ring.wav'))

    def warning(self,string,rows=0):
        # print("do warning")
        self.show_messagebox(string,rows)
        
class monitor_pc(object):
    def __init__(self):
        self.logger = logging.getLogger('mylogger')
        self.logger.setLevel(logging.DEBUG)
        import datetime
        rf_handler = logging.handlers.TimedRotatingFileHandler('all.log', when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
        rf_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
        self.logger.addHandler(rf_handler)
        # logger.addHandler(f_handler)

        # logger.debug('debug message')
        # logger.info('info message')
        # logger.warning('warning message')
        # logger.error('error message')
        # logger.critical('critical message')
        
        # self.workDir = 'D:/Monitor'#os.getcwd()
        self.workDir = os.getcwd()
        self.nircmdDir = '%s/tools'%self.workDir
        self.scrCaptureDir = self.workDir
        self.scrShot_path = "%s/ScrShots"%self.workDir
        self.db_path = "%s/db"%self.workDir
        if not os.path.exists(self.scrShot_path):
            os.mkdir(self.scrShot_path)
        #self.app = Application()
        self.version = '1.0.3'
        self.logger.info(self.version)

        self.cfg = {}
        try:
            cfg_file = '%s\\config.json'%self.db_path
            with open(cfg_file, 'r',encoding="utf-8") as cfg:
                self.cfg = json.load(cfg)
                
        except Exception as e:
            self.cfg = config
            self.logger.error(e)
    
    # def system_is_admin(self):
    #     """
    #     :return:
    #     """
    #     try:
    #         return ctypes.windll.shell32.IsUserAnAdmin()
    #     except Exception as e:
    #         #logger.warning(e)
    #         return False
    def config_file_write(self,file,json_data):
        cfg_file = '%s\\%s'%(self.db_path,file)
        with open(cfg_file, mode='w',encoding="utf-8") as wf:  # 以写方式打开json文件
            json.dump(json_data, wf, ensure_ascii=False, indent=4)  # ensure_ascii=False 可支持输出中文，indent设置缩进
            
    def get_current_time(self):
        ct = time.time()
        local_time = time.localtime(ct)
        time_stamp = time.strftime("%H%M%S", local_time)
        return time_stamp
    
    def get_current_date(self):
        ct = time.time()
        local_time = time.localtime(ct)
        date_head = time.strftime("%Y-%m-%d", local_time)
        return date_head
    
    def screenShot(self):
        cur_date = self.get_current_date()
        scr_path = "%s\\%s"%(self.scrShot_path,cur_date)
        if not os.path.exists(scr_path):
            os.mkdir(scr_path)
        
        def calculate_days(start_date, end_date):
            delta = end_date - start_date
            return delta.days

        for root, dirs, files in os.walk(self.scrShot_path):
            # print(dirs)
            for dir in dirs:
                start_date = date(int(dir.split('-')[0]), int(dir.split('-')[1]), int(dir.split('-')[2]))
                end_date = date(int(cur_date.split('-')[0]), int(cur_date.split('-')[1]), int(cur_date.split('-')[2]))
                days = calculate_days(start_date, end_date)
                if days > 7:
                    shutil.rmtree(self.scrShot_path+"/"+dir)
            # print(files)
    
        cur_time = self.get_current_time() 
        scr_name = r"%s\\ScrShots_%s.jpg"%(scr_path,cur_time)
        self.logger.info('ScrShot:%s'%(scr_name))
        img = pyautogui.screenshot()
        img.save(scr_name) 
    
    def write_csv(self,csvfile,data):
        #array=[["姓名","年龄","性别"],["吴金红","30","男"],["姜峰","24","女"],["雷建国","60","男"]]
        # rows = []
        rows=zip(data)
        with open(csvfile, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerows(rows)
                
    def get_processes(self):
        processes = []
        try:
            pids = psutil.pids()
            #print(pids)
            for pid in pids:
                p = psutil.Process(pid)
                # get process name according to pid
                process_name = p.name()
                #print(process_name)
                processes.append(process_name)
            
            #print(processes)
            # csv_file = '%s\\processes.csv'%self.db_path
            # self.write_csv(csv_file,processes)
        except:
            pass
        return processes
    
    def find_processes(self,procname):
        isfind = False
        try:
            pids = psutil.pids()
            #print(pids)
            for pid in pids:
                p = psutil.Process(pid)
                # get process name according to pid
                process_name = p.name()
                #print(process_name)
                for proc in procname:
                    if process_name.lower().find(str(proc).lower())!= -1:
                    #if str(proc).lower().find(process_name.lower()) != -1:
                        self.logger.info("Process name is: %s, pid is: %s" %(process_name, pid))
                        #self.show(process_name)
                        isfind = True
        except:
            pass
                    
        return isfind
                               
    def kill_processes(self,procname):
        try:
            pids = psutil.pids()
            for pid in pids:
                p = psutil.Process(pid)
                # get process name according to pid
                process_name = p.name()
                # kill process 
                for proc in procname:
                    if process_name.lower().find(str(proc).lower())!= -1:
                    #if str(proc).lower().find(process_name.lower()) != -1:
                        # print("kill specific process: name(%s)-pid(%s)" %(process_name, pid))
                        self.logger.info("kill specific process: name(%s)-pid(%s)" %(process_name, pid))
                        try:
                            os.kill(pid, signal.SIGINT)
                        except:
                            pass
        except:
            pass
        
    def get_unnormal_precesses(self,all_proc):
        try:
            unnormal_precesses=[]
            pids = psutil.pids()
            #print(pids)
            for pid in pids:
                p = psutil.Process(pid)
                # get process name according to pid
                process_name = p.name()
                if not (process_name in all_proc):
                    # process_name = process_name.replace('.exe','')
                    process_name = process_name.strip()
                    unnormal_precesses.append(process_name)
            #print(unnormal_precesses)
        except:
            pass
        
        return unnormal_precesses

    def judge_time(self,times):
        
        isfind = False
        now_localtime = time.strftime("%H:%M:%S", time.localtime())
        now_time = Interval(now_localtime, now_localtime)

        for t in times:
            #print(now_time)
            if (not t) or (t.find('-')==-1):
                continue
            ts = t.split('-')
            time_interval = Interval(ts[0], ts[1])
            #print(time_interval)

            if now_time in time_interval:
                isfind = True
                # self.logger.info("now_time in time_interval...")
            else:
                pass
                # self.logger.info("now_time not in time_interval...")
        return isfind
    
    def is_english_class(self):
        
        # self.logger.info("jusge is english class")
        
        # self.logger.info('English class time:%s'%self.cfg["englishclass_list"])
        # print(self.cfg["englishclass_list"])
        year=time.localtime().tm_year
        month=time.localtime().tm_mon
        day=time.localtime().tm_mday
        date =datetime.date(datetime(year=year,month=month,day=day))
           
        # print(date.strftime("%A"))
        # print(date.isoweekday())
        # print(date.weekday())
        # print(week_list[date.isoweekday()])
        # print(week_list[date.weekday()+1])
        
        english_class = False
        english_time = []
        if self.cfg["englishclass_list"][date.weekday()] !='':
            english_time = self.cfg["englishclass_list"][date.weekday()].split('-')
        else:
            return english_class

        
        now_localtime = time.strftime("%H:%M:%S", time.localtime())
        now_time = Interval(now_localtime, now_localtime)

        # print(now_time)
        time_interval = Interval(english_time[0], english_time[1])
        #print(time_interval)

        if now_time in time_interval:
            english_class = True
            # self.logger.info("now time: %s is english class..."%now_time)
        else:
            pass
            # self.logger.info("now time: %s is not english class..."%now_time)
        return english_class
    
    def screen_Shot(self,thread_name):
        #monpc = monitor_pc()
        self.logger.info(thread_name)
        times = self.cfg["time_arg"]
        intime = self.judge_time(times)
        while(True):
            if intime:
                self.screenShot()
                time.sleep(60)
            else:
                time.sleep(0.1)
                
    def baidu_syncup(self,thread_name,scrShot_path):
        print(thread_name)
        bp = ByPy()
        try:
            while(True):
                bp.syncup(localdir=scrShot_path, remotedir=u'ScrShots/', deleteremote=False)
                time.sleep(0.1)
        except Exception as e:
            pass

            
    def baidu_syncup1(self,thread_name,scrShot_path):
        os.system("bdsyncup.bat")
        time.sleep(0.1)

@pidfile()
def run():
    monpc = monitor_pc()
    monpc.logger.info("start thread for baidu_syncup...")
    thread_01 = Thread(target=monpc.baidu_syncup, args=("baidu_syncup",monpc.scrShot_path), name="baidu_syncup")
    # thread_01 = Thread(target=monpc.baidu_syncup1, args=("baidu_syncup",monpc.scrShot_path), name="baidu_syncup")
    thread_01.daemon=True
    thread_01.start()
    
    monpc.logger.info("start thread for screen_Shot...")
    thread_02 = Thread(target=monpc.screen_Shot, args=["screen_Shot"],name="screen_Shot")
    thread_02.daemon=True
    thread_02.start()
    
    times = monpc.cfg["time_arg"]
    if times.__len__() < 1:
        monpc.logger.info("please input correct time interval arg...")
        os.exit(2)
        
    allow_game = 0
    allow_music = 0
    allow_brower = 0
    is_en_class = False
    is_rest_time = False
    Count = 0
    loops = 2
    try:
        setting_file = '%s\\setting.json'%monpc.db_path
        with open(setting_file, 'r',encoding="utf-8") as s:
            setting = json.load(s)
            loops = setting["loops"]
            interval_time = setting["interval_time"]
            interval_time_idx =setting["interval_time_idx"]
            allow_music = setting["allow_music"]
            allow_game = setting["allow_game"]
            allow_brower = setting["allow_brower"]
    except Exception as e:
        interval_time = [5,10,20,30,60]
        interval_time_idx = 1
        monpc.logger.error(loops)
        monpc.logger.error(e)
    
    while(True):
        if loops==3:
            break
        intime = monpc.judge_time(times)
        if intime and loops==2:
            is_en_class = monpc.is_english_class()
            # monpc.logger.info("judge rest time.")
            rest = monpc.cfg["rest_time"]
            is_rest_time = monpc.judge_time(rest)
            if is_rest_time:
                monpc.logger.info("is rest time.")

            if is_en_class:
                monpc.logger.info("is english class time.")
                if monpc.find_processes(monpc.cfg["game_proc"]):
                    monpc.kill_processes(monpc.cfg["game_proc"])
                    message_show().warning("警告！！上课期间严禁打游戏...")
                Count += 1
                time.sleep(60)
                if Count >= 7:
                    Count = 0
                    if (not allow_game) and monpc.find_processes(monpc.cfg["game_proc"]):
                        monpc.kill_processes(monpc.cfg["game_proc"])
                        message_show().warning("警告！！上课期间严禁打游戏...")
                    if (not allow_brower) and monpc.find_processes(monpc.cfg["brower_proc"]):
                        monpc.kill_processes(monpc.cfg["brower_proc"])
                        message_show().warning("警告！！上课期间严禁打开浏览器...")
                    if (not allow_music) and monpc.find_processes(monpc.cfg["music_proc"]):
                        monpc.kill_processes(monpc.cfg["music_proc"])
                        message_show().warning("警告！！上课期间严禁打开音乐播放器...")

                    unnormal_precesses = monpc.get_unnormal_precesses(monpc.cfg["all_processes"])
                    kills = []
                    for unnormal in unnormal_precesses:
                        if (unnormal in monpc.cfg["game_proc"]) and allow_game or\
                           (unnormal in monpc.cfg["music_proc"]) and allow_music or\
                           (unnormal in monpc.cfg["brower_proc"]) and allow_brower:
                            pass
                        else:
                            if not (unnormal in kills):
                                kills.append(unnormal)
                            # kills = list(filter(lambda x: x != unnormal, unnormal_precesses))

                    if kills:
                        monpc.logger.info(kills)
                        monpc.kill_processes(kills)
                        for kill in kills:
                            if kill not in monpc.cfg["unnormal_proc"]:
                                monpc.cfg["unnormal_proc"].append(kill)
                                monpc.logger.info(monpc.cfg["unnormal_proc"])
                                monpc.config_file_write("config.json",monpc.cfg)
                        message_show().warning("警告！！(%s)非法进程启动..."%(",".join(kills)),1)
                    else:
                        pass
            else:
                if (not allow_game) and monpc.find_processes(monpc.cfg["game_proc"]):
                    monpc.kill_processes(monpc.cfg["game_proc"])
                    message_show().warning("警告！！上课期间严禁打游戏...")
                if (not allow_brower) and monpc.find_processes(monpc.cfg["brower_proc"]):
                    monpc.kill_processes(monpc.cfg["brower_proc"])
                    message_show().warning("警告！！上课期间严禁打开浏览器...")
                if (not allow_music) and (not is_rest_time) and monpc.find_processes(monpc.cfg["music_proc"]):
                    monpc.kill_processes(monpc.cfg["music_proc"])
                    message_show().warning("警告！！上课期间严禁打开音乐播放器...")
                
                unnormal_precesses = monpc.get_unnormal_precesses(monpc.cfg["all_processes"])
                kills = []
                for unnormal in unnormal_precesses:
                    if (unnormal in monpc.cfg["game_proc"]) and allow_game or\
                        (unnormal in monpc.cfg["music_proc"]) and allow_music or\
                        (unnormal in monpc.cfg["brower_proc"]) and allow_brower:
                            pass
                    else:
                        if not (unnormal in kills):
                            kills.append(unnormal)
                            # kills = list(filter(lambda x: x != unnormal, unnormal_precesses))
                    
                if kills:
                    monpc.logger.info(kills)
                    # unnormal_precesses.extend(process)
                    monpc.kill_processes(kills)
                    for kill in kills:
                        if kill not in monpc.cfg["unnormal_proc"]:
                            monpc.cfg["unnormal_proc"].append(kill)
                            monpc.logger.info(monpc.cfg["unnormal_proc"])
                            monpc.config_file_write("config.json",monpc.cfg)
                    message_show().warning("警告！！(%s)非法进程启动..."%(",".join(kills)),1)
                else:
                    # monpc.logger.info("not find unnormal process...")
                    pass         

        for i in range(0,interval_time[interval_time_idx]):
            try:
                setting_file = '%s\\setting.json'%monpc.db_path
                with open(setting_file, 'r',encoding="utf-8") as s:
                    setting = json.load(s)
                    loops = setting["loops"]
                    interval_time_idx =setting["interval_time_idx"]
                    allow_music = setting["allow_music"]
                    allow_game = setting["allow_game"]
                    allow_brower = setting["allow_brower"]
                    
                cfg_file = '%s\\config.json'%monpc.db_path
                with open(cfg_file, 'r',encoding="utf-8") as cfg:
                    monpc.cfg = json.load(cfg)
            except Exception as e:
                monpc.logger.error(e)
                
            if loops==0:
                monpc.logger.info("Stop.")
            elif loops==1:
                monpc.logger.info("Pause.")
            elif loops==2:
                monpc.logger.info("Working...")
            else:
                monpc.logger.info("Exit.")
                
            time.sleep(1)
       
if __name__ == '__main__':
    run()
